<template>
  <h1>Sku管理</h1>
  
  <el-row>
    <el-col :span="23">
      <el-button type="primary"
                 v-if="authority.skuInfoAdd"
                @click="add()">添加sku</el-button>
      <el-input v-model="query"
                style="width:200px;margin-left:15px"
                @input="filter()"
                placeholder="搜索sku">
        <template #prefix>
          <el-icon class="el-input__icon">
            <search />
          </el-icon>
        </template>
      </el-input>
    </el-col>
    <el-col :span="1"><el-button @click="back()" type="warning" size="small">返回</el-button></el-col>
  </el-row>
  <el-table :data="pageInfo.list"
            stripe
            border
            style="width: 100%"
            :header-cell-style="{textAlign:'center'}"
            :cell-style="{textAlign:'center'}">
    <el-table-column
        fixed
        prop="skuName"
        label="商品名称">
    </el-table-column>
    <el-table-column
        prop="skuDesc"
        label="商品描述"
        :show-overflow-tooltip="true">
    </el-table-column>
    <el-table-column
        prop="skuTitle"
        :show-overflow-tooltip="true"
        label="标题">
    </el-table-column>
    <el-table-column
        prop="skuSubtitle"
        :show-overflow-tooltip="true"
        label="副标题">
    </el-table-column>
    <el-table-column
        prop="price"
        label="价格">
    </el-table-column>
    <el-table-column
        prop="saleCount"
        label="销量">
    </el-table-column>
    <el-table-column
        fixed="right"
        label="操作"
        width="450px">
      <template #default="scope">
        <el-button color="#00B2EE" style="color:azure" size="small" @click="toDetail(scope)">
          详细信息
        </el-button>
        <el-button color="#f36c21" style="color:azure" @click="toSkuAttr(scope)" size="small">
          属性管理
        </el-button>
        <el-button
          @click="toImageManage(scope)"
          color="#626aef"
          size="small">
          图片管理
        </el-button>
        <el-button
          v-if="authority.skuInfoUpdate"
          @click="edit(scope)"
          type="primary"
          size="small">
          编辑
        </el-button>
        <el-button
          v-if="authority.skuInfoDelete"
          @click="del(scope)"
          type="danger"
          size="small">
          删除
        </el-button>
        
      </template>
    </el-table-column>
  </el-table>

  <el-pagination class="el-pagination"
                 layout="prev,pager,next,total,jumper,sizes"
                 :total="pageInfo.total"
                 v-model:current-page="pageInfo.pageNum"
                 v-model:page-size="pageInfo.pageSize"
                 :page-sizes="[3,5,10,20]"
                 background
                 @current-change="handleCurrentChange"
                 @size-change="handleSizeChange">
  </el-pagination>

  <el-drawer v-model="drawer_sku" title="title—useless" :with-header="false" size="35%">
      <span><h4>Sku详情信息</h4></span>
      <el-divider></el-divider>
      <span>
          <el-descriptions
              class="margin-top"
              :column="3"
              :size="small"
              :style="blockMargin"
              border
          >
              <el-descriptions-item label="商品名称">{{SkuInfo.skuName}}</el-descriptions-item>
              <el-descriptions-item label="商品描述">{{SkuInfo.skuDesc}}</el-descriptions-item>
              <el-descriptions-item label="商品价格">{{SkuInfo.price}}</el-descriptions-item>
              <el-descriptions-item label="商品标题" span="3">{{SkuInfo.skuTitle}}</el-descriptions-item>
              <el-descriptions-item label="商品子标题">{{SkuInfo.skuSubtitle}}</el-descriptions-item>
          </el-descriptions>
      </span>
  </el-drawer>

  <el-dialog title="编辑Sku商品信息" v-model="disableDialog" width="600px" center>
    <el-form :model="skuInfo"
             :rules="rules"
             ref="editSkuInfo"
             label-width="90px">
      <el-form-item label="sku名称"
                    prop="skuName">
        <el-input v-model="skuInfo.skuName"
                  placeholder="请输入商品名称"></el-input>
      </el-form-item>
      <el-form-item label="sku描述"
                    prop="skuDesc">
        <el-input autosize
                  type="textarea"
                  v-model="skuInfo.skuDesc"
                  placeholder="请输入商品描述"></el-input>
      </el-form-item>
      <el-form-item label="sku标题"
                    prop="skuTitle">
        <el-input autosize
                  type="textarea"
                  v-model="skuInfo.skuTitle"
                  placeholder="请输入商品标题"></el-input>
      </el-form-item>
      <el-form-item label="sku副标题"
                    prop="skuSubtitle">
        <el-input autosize
                  type="textarea"
                  v-model="skuInfo.skuSubtitle"
                  placeholder="请输入商品副标题"></el-input>
      </el-form-item>
      <el-form-item label="sku价格"
                    prop="price">
        <el-input-number placeholder="价格(元)" v-model="skuInfo.price" :precision="2" :step="0.1" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="cancelSave('editSkuInfo')">取消</el-button>
      <el-button type="primary"
                 @click="saveData('editSkuInfo')">保存</el-button>
    </template>
  </el-dialog>
  
  <el-dialog title="添加Sku商品信息" v-model="addDisableDialog" width="600px" center>
    <el-form :model="skuInfo"
             label-position="left"
             :rules="rules"
             ref="addSkuInfo"
             label-width="90px">
      <el-form-item label="sku名称"
                    prop="skuName">
        <el-input v-model="skuInfo.skuName"
                  placeholder="请输入商品名称"></el-input>
      </el-form-item>
      <el-form-item label="sku描述"
                    prop="skuDesc">
        <el-input autosize
                  type="textarea"
                  v-model="skuInfo.skuDesc"
                  placeholder="请输入商品描述"></el-input>
      </el-form-item>
      <el-form-item label="sku标题"
                    prop="skuTitle">
        <el-input autosize
                  type="textarea"
                  v-model="skuInfo.skuTitle"
                  placeholder="请输入商品标题"></el-input>
      </el-form-item>
      <el-form-item label="sku副标题"
                    prop="skuSubtitle">
        <el-input autosize
                  type="textarea"
                  v-model="skuInfo.skuSubtitle"
                  placeholder="请输入商品副标题"></el-input>
      </el-form-item>
      <el-form-item label="sku价格"
                    prop="price">
        <el-input-number placeholder="价格(元)" v-model="skuInfo.price" :precision="2" :step="0.1" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="cancelSave('addSkuInfo')">取消</el-button>
      <el-button type="primary"
                 @click="saveData('addSkuInfo')">添加</el-button>
    </template>
  </el-dialog>

  <el-drawer
    v-model="drawer"
    title="图片管理"
    direction="rtl"
    :size="500"
    >
    <el-button type="primary" @click="toAddImage" size="small">添加图片</el-button>
    <el-table border :data="imageList" :header-cell-style="{textAlign:'center'}" max-height="591px">
    <el-table-column  label="图片">
      <template #default="scope" width="110px">
        <el-image style="width:100px;height:100px" :src="scope.row.img" fit="contain" >
        </el-image>
      </template>
    </el-table-column>
    <el-table-column  width="270px" 
                     label="操作">
      <template #default="scope">
        <el-button size="small" type="primary" v-if="scope.row.defaultImg != 1" @click="setDefaultImage(scope)">设置为默认</el-button>
        <el-button size="small" type="danger" @click="deleteImage(scope)">删除</el-button>
      </template>
    </el-table-column>
    </el-table>
  </el-drawer>

  <el-dialog v-model="uploadImage" title="上传图片" width="550px">
  <span>一次性最多上传5张照片，超出的会替换第五张</span>
  <el-upload 
            :action="''"
            list-type="picture-card" 
            :auto-upload="false"
            :before-upload="getPolicy"
            :on-change="change"
            :on-exceed="exceedHandle"
            :http-request="go"
            :limit="5"
            ref="uploadImageRef" >
    <el-icon><Plus /></el-icon>

    <template #file="{ file }">
      <div>
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions">
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
          >
            <el-icon><Delete /></el-icon>
          </span>
        </span>
      </div>
    </template>
  </el-upload>

  <template #footer>
    <el-button @click="cancelUpload">取消</el-button>
    <el-button type="primary" @click="upload" >上传</el-button>
  </template>
  </el-dialog>
</template>

<script>
import { genFileId } from 'element-plus'
import {ref, getCurrentInstance} from 'vue'
import axios from 'axios';
  export default {
    name: "SkuInfo",

    created() {
      this.initSpuId()
      this.showData()
      this.initAuthority()
    },
    setup(){
      const uploadImageRef = ref()
      const {proxy} = getCurrentInstance()

      const change = (file,fileList) => {
        proxy.fileList = fileList
      }

      const drawer_sku = ref(false);
      const SkuInfo = ref({})
      const toDetail = (scope) => {
        SkuInfo.value = {...scope.row}
        drawer_sku.value = true;
      }

      const handleRemove = (file) => {
        uploadImageRef.value.handleRemove(file)
      }

      const exceedHandle = (files) => {
        uploadImageRef.value.handleRemove(proxy.fileList[4])
        const file = files[0]
        file.uid = genFileId()
        uploadImageRef.value.handleStart(file)
      }

      return {uploadImageRef,SkuInfo,drawer_sku,change,handleRemove,exceedHandle,toDetail}
    },
    data() {
      return {
        query: '',
        authority: {
          total: false,
          skuInfoAdd: false,
          skuInfoDelete: false,
          skuInfoUpdate: false
        },
        drawer:false,
        nowSkuId:null,
        uploadImage:false,
        imageList:[],
        objectDataMap:new Map(),
        fileList:[],
        rules: {
          skuName: [
            { required: true, message: "商品名称不能为空", trigger: ['change', 'blur'] },
            { min: 1, max: 10, message: '商品名长度必须在1-10个字符之间', trigger: ['blur', 'change'] },
          ],
          skuDesc: [
            { required: true, message: "请输入商品描述", trigger: ['blur', 'change'] },
            { min: 1, max: 100, message: '商品描述不能超过100个字符', trigger: ['blur', 'change'] },
          ],
          skuTitle: [
            { required: true, message: "请输入商品标题", trigger: ['blur', 'change'] },
            { min: 1, max: 50, message: '商品标题不能超过50个字符', trigger: ['blur', 'change'] },
          ],
          skuSubtitle: [
            { required: true, message: "请输入商品子标题", trigger: ['blur', 'change'] },
            { min: 1, max: 100, message: '商品子标题不能超过100个字符', trigger: ['blur', 'change'] },
          ],
          price: [
            { required: true, message: "请输入商品价格", trigger: ['blur', 'change'] },
          ]
        },
        categoryId:this.$route.query.categoryId,
        brandId:this.$route.query.brandId,
        spuId:0,
        categoryName:this.$route.query.categoryName,
        brandName:this.$route.query.brandName,
        spuName:this.$route.query.spuName,
        skuInfo:{
        },
        pageInfo: {
          pageNum: 1,
          pageSize: 5,
        },
        disableDialog: false,
        addDisableDialog: false,
      }
    },

    methods: {
      initSpuId(){
        this.spuId = this.$route.query.spuId
      },
      initAuthority () {
        this.authority.total = this.$store.state.authority[this.$power.map.get("商品管理-Sku管理").property]
        this.authority.skuInfoAdd = this.$store.state.authority[this.$power.map.get("商品管理-Sku管理-添加").property]
        this.authority.skuInfoUpdate = this.$store.state.authority[this.$power.map.get("商品管理-Sku管理-修改").property]
        this.authority.skuInfoDelete = this.$store.state.authority[this.$power.map.get("商品管理-Sku管理-删除").property]
        Object.freeze(this.authority)
        this.$power.totalCheckAuthority(this.authority)
      },
      toSkuAttr(scope){
        this.$router.push({ path:'/main/product/skuAttr', query:{
          categoryName:this.categoryName,
          categoryId:this.categoryId,
          brandName:this.brandName,
          spuName:this.spuName,
          skuName:scope.row.skuName,
          skuDesc:scope.row.skuDesc,
          skuId:scope.row.id,
          spuId:this.spuId
        }})
      },
      go(data){
        let form = new FormData()
        let uid = data.file.uid
        let object = this.objectDataMap.get(data.file.uid)
        form.append("OSSAccessKeyId",object.OSSAccessKeyId)
        form.append("policy",object.policy)
        form.append("Signature",object.Signature)
        form.append("dir",object.dir)
        form.append("key",object.key)
        form.append("host",object.host)
        form.append("file",data.file)
        axios.create().post(object.host,form).then(()=>{
          this.objectDataMap.delete(uid)
          this.uploadSuccess(object.url)
        }).catch(err=>{
          this.uploadError(err)
        })
      },
      setDefaultImage(scope){
        this.$http.get(this.$url.PmsSkuImagesControllerBaseUrl + '/setDefault',{params:{skuId:this.nowSkuId,id:scope.row.id}})
          .then(res => {
            if(res.data.code === 2000){
              this.$message({
                message:res.data.message,
                type:'success'
              })
              this.getImageList()
            }else{
              this.$message({
                message:res.data.message,
                type:'error'
              })
            }
          })
      },
      toImageManage(scope){
        this.nowSkuId = scope.row.id
        this.getImageList()
        this.drawer = true
      },
      deleteImage(scope){
        this.$http.delete(this.$url.PmsSkuImagesControllerBaseUrl + '/deleteImage',{params:{id:scope.row.id}})
          .then(res => {
            if(res.data.code === 2000){
              this.$message({
                message:res.data.message,
                type:'success'
              })
              this.getImageList()
            }else{
              this.$message({
                message:res.data.message,
                type:'error'
              })
            }
          })
      },
      toAddImage(){
        this.uploadImage = true
        if(this.uploadImageRef){
          this.uploadImageRef.clearFiles()
        }
      },
      uploadSuccess(url){
        let data = {skuId:this.nowSkuId,img:url}
        this.$http.put(this.$url.PmsSkuImagesControllerBaseUrl + '/addImage',data)
          .then(res => {
            if(res.data.code === 2000){
              this.$message({
                message:res.data.message,
                type:'success'
              })
              this.getImageList()
              this.cancelUpload()
            }else{
              this.$message({
                message:res.data.message,
                type:'error'
              })
            }
          })
      },
      getPolicy(file){
        return new Promise(((resolve,reject) => {
                this.$http.get(this.$url.OSSControllerBaseUrl + '/getPolicyForSku',{
                  params:{
                    skuId:this.nowSkuId
                  }
                }).then(res => {
                  let objectData = {}
                  objectData.OSSAccessKeyId = res.data.data.accessid;
                  objectData.policy = res.data.data.policy;
                  objectData.Signature = res.data.data.signature;
                  objectData.dir = res.data.data.dir;
                  objectData.host = res.data.data.host;
                  objectData.key = res.data.data.key;
                  objectData.url = objectData.host + '/' + objectData.key
                  this.objectDataMap.set(file.uid,objectData)
                  resolve(true)
                })
                .catch(err =>{
                  console.log(err)
                  reject(false)
                })
              }))
      },
      getImageList(){
        this.$http.get(this.$url.PmsSkuImagesControllerBaseUrl + '/getBySkuId',{params:{skuId:this.nowSkuId}})
          .then(res => {
            if(res.data.code === 2000){
              this.imageList = res.data.data
            }
          })
      },
      cancelUpload(){
        this.uploadImage = false
      },
      upload(){
        this.uploadImageRef.submit()
      },
      back(){
        this.$router.push({ path:'/main/product/spuinfo' })
      },
      handleCurrentChange () {
        this.showData();
      },
      handleSizeChange () {
        this.showData();
      },
      // 获取所有的sku数据
      showData(){
        let params = {
          pageNum: this.pageInfo.pageNum,
          pageSize: this.pageInfo.pageSize,
          spuId: this.spuId,
        }
        let url = this.$url.PmsSkuInfoControllerBaseUrl + '/getPaged';
        this.$http.get(url, {params:params}).then(res => {
          if(res.data.code == 2000) {
            this.pageInfo = res.data.data
          }
        })
      },

      // 根据关键字搜索相应的sku数据
      selectBySkuName(skuName){
        let params = {
          pageNum: this.pageInfo.pageNum,
          pageSize: this.pageInfo.pageSize,
          skuName: skuName,
          spuId: this.spuId
        }
        let url = this.$url.PmsSkuInfoControllerBaseUrl + '/selectBySkuName';
        this.$http.get(url, {params:params}).then(res => {
          if(res.data.code == 2000){
            this.pageInfo = res.data.data
          }
        })
      },

      // 根据id删除相应的sku数据
      del(scope){
        this.$confirm('是否删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let url = this.$url.PmsSkuInfoControllerBaseUrl + `/check/deleteSku?skuId=${scope.row.id}`;
          this.$http.delete(url).then(res => {
            if(res.data.code == 2000){
              this.$message({
                message: res.data.message,
                type: "success"
              })
            }else {
              this.$message({
                message: res.data.message,
                type: "error"
              })
            }
            this.showData()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },

      // 添加sku
      add(){
        this.addDisableDialog = true;
        this.skuInfo = {};
        this.skuInfo.categoryId = this.categoryId;
        this.skuInfo.brandId = this.brandId;
        this.skuInfo.spuId = this.spuId
      },
      //编辑sku
      edit(scope){
        this.disableDialog = true;
        this.skuInfo = {};
        this.skuInfo = {...scope.row};
        this.skuInfo.categoryId = this.categoryId;
        this.skuInfo.brandId = this.brandId;
        this.skuInfo.spuId = this.spuId
      },

      //搜索框
      filter(){
        let query = this.query
        if(query == ''){
          this.showData()
        }else{
          this.selectBySkuName(query)
        }
      },

      cancelSave(ref_name){
        if (this.disableDialog) {
          this.mes = "已取消保存"
        }
        if (this.addDisableDialog) {
          this.mes = "已取消添加"
        }
        this.$confirm("数据尚未保存，是否取消？", "提示", {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (this.disableDialog) {
            this.$refs[ref_name].resetFields();
            this.disableDialog = false;
          }
          if (this.addDisableDialog) {
            this.$refs[ref_name].resetFields();
            this.addDisableDialog = false;
          }
          this.spuInfo = {}
          this.$message({
            type: 'info',
            message: this.mes
          });
        })
      },

      saveData (ref_name) {
        this.$refs[ref_name].validate((valid) => {
          if (valid) {
            if (this.disableDialog) {
              this.$confirm("数据即将保存，是否确认？", "提示", {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                let url = this.$url.PmsSkuInfoControllerBaseUrl + "/check/update";
                this.$http.post(url, this.skuInfo).then(res => {
                  if (res.data.code === 2000) {
                    this.$message({
                      type: 'success',
                      message: '保存成功!'
                    });
                    this.$refs[ref_name].resetFields();
                    this.disableDialog = false;
                    this.showData();
                    this.skuInfo = {};
                  } else {
                    this.$message({
                      type: 'error',
                      message: res.data.message
                    });
                  }
                })
              })
            }
            if (this.addDisableDialog) {
              this.$confirm("数据即将保存并添加，是否确认？", "提示", {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                let url = this.$url.PmsSkuInfoControllerBaseUrl + "/check/insert";
                this.$http.post(url, this.skuInfo).then(res => {
                  if (res.data.code === 2000) {
                    this.$message({
                      type: 'success',
                      message: '添加成功!'
                    });
                    this.$refs[ref_name].resetFields();
                    this.addDisableDialog = false;
                    this.showData();
                    this.skuInfo = {};
                    this.pageInfo.pageNum = 1;
                  } else {
                    this.$message({
                      type: 'error',
                      message: res.data.message
                    });
                  }
                })
              })
            }
          }
        })
        this.showData()
      },
    },
  }
</script>

<style scoped>

</style>
